package cn.ad.server.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author dongbin.yu
 * @from 2016-05-31
 * @since V1.0
 */
public class BrowserUtils {

	private static Pattern regexIE = Pattern.compile("MSIE (([\\d]+)\\.([\\w]+))", Pattern.CASE_INSENSITIVE);
	private static Pattern regexFireFox = Pattern.compile("Firefox\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)",
			Pattern.CASE_INSENSITIVE);
	private static Pattern regexChrome = Pattern.compile("Chrome[\\s/]?(\\d*)", Pattern.CASE_INSENSITIVE);
	private static Pattern regexOpera = Pattern.compile("Opera[\\s/]?(\\d*)", Pattern.CASE_INSENSITIVE);
	private static Pattern regexSafari = Pattern.compile("AppleWebKit", Pattern.CASE_INSENSITIVE);
	private static Pattern regexMaxthon = Pattern.compile("Maxthon[\\s/]?(\\d*)", Pattern.CASE_INSENSITIVE);
	private static Pattern regexTencentTraveler = Pattern.compile("\bTencent\\s?Traveler[\\s/]?(\\d*)",
			Pattern.CASE_INSENSITIVE);
	private static Pattern regexSougouBroswer = Pattern.compile("SE.*MetaSr", Pattern.CASE_INSENSITIVE);
	private static Pattern regexTheWorldBrowser = Pattern.compile("TheWorld[\\s/]?(\\d*)", Pattern.CASE_INSENSITIVE);
	private static Pattern regexBrowser360 = Pattern.compile("360SE", Pattern.CASE_INSENSITIVE);

	private static HashMap<Browser, Pattern> browserRegexMap = null;

	static {
		browserRegexMap = new HashMap<Browser, Pattern>();
		browserRegexMap.put(Browser.BROWSER_360, regexBrowser360);
		browserRegexMap.put(Browser.IE, regexIE);
		browserRegexMap.put(Browser.SOUGOU_BROWSER, regexSougouBroswer);
		browserRegexMap.put(Browser.FIREFOX, regexFireFox);
		browserRegexMap.put(Browser.CHROME, regexChrome);
		browserRegexMap.put(Browser.TENCENT_TRAVERLER, regexTencentTraveler);
		browserRegexMap.put(Browser.THEWORLD_BROWSER, regexTheWorldBrowser);
		browserRegexMap.put(Browser.MAXTHON, regexMaxthon);
		browserRegexMap.put(Browser.OPERA, regexOpera);
		browserRegexMap.put(Browser.SAFARI, regexSafari);
	}

	public static String getBrowser(String userAgent) {
		if (userAgent == null) {
			return Browser.OTHER.toString();
		}

		userAgent = userAgent.toLowerCase();
		for (Map.Entry<Browser, Pattern> item : browserRegexMap.entrySet()) {

			Matcher name = item.getValue().matcher(userAgent);
			if (name.find()) {
				return item.getKey().toString();
			}
		}

		return Browser.OTHER.toString();
	}

	private enum Browser {
		OTHER, IE, FIREFOX, CHROME, OPERA, SAFARI, MAXTHON, TENCENT_TRAVERLER, SOUGOU_BROWSER, THEWORLD_BROWSER, BROWSER_360
	}
}
